from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData


# 加密
def generate_openid_signature(openid):
    """
    对openid进行加密
    :param openid: 要加密的openid数据
    :return: 加密后的openid
    """
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)

    data = {'openid': openid}

    openid = serializer.dumps(data)     # 加密后返回的数据是bytes类型
    return openid.decode()



# 解密
def check_openid_sign(openid):
    """
    对加密后的openid进行解密,回到原本样子
    :param openid_sign: 要解密的openid
    :return: 原本的openid
    """

    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)

    try:
        data = serializer.loads(openid)
    except BadData:
        return None

    else:
        return data.get('openid')


